/**
 * 
 */
package com.runningfox.humor;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.runningfox.model.Comment;
import com.runningfox.model.Joke;

/**
 * @author lhy
 * 
 */
public class JokeDetailListAdapter extends BaseAdapter {
	ArrayList list;
	Humor callback;
	public JokeDetailListAdapter(Humor callback){
		this.callback =callback;
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list!=null?list.size():0;
	}
	
	public void updateNode(Object node){
		int size = list.size();
		for(int i=0;i<size;i++){
			Object cur = list.get(i);
			if(cur!=null&& cur instanceof Joke&&node instanceof Joke){
				Joke curjoke =(Joke)cur;
				Joke joke = (Joke)node;
				if(curjoke.id==joke.id){
					this.list.remove(i);
					this.list.add(i, joke);
					return;
				}
			}
		}
	}

	public void setList(ArrayList list){
		this.list=list;
	}
	
	public void add(Object o){
		list.add(o);
	}
	
	public void addAll(ArrayList l){
		list.addAll(l);
	}
	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		Object o = list.get(position);
		if(o instanceof Joke){
			return ((Joke)o).id;
		}else if(o instanceof Comment){
			return ((Comment)o).id;
		}
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Object node = list.get(position);
		View view=null;
		if (node instanceof Joke) {
			Joke jokenode = (Joke) list.get(position);
			if (convertView == null||(convertView!=null&&!(convertView instanceof JokeNodeView))) {
				view = new JokeNodeView(callback, jokenode);
			} else {
				view = (JokeNodeView) convertView;
				((JokeNodeView)view).setNode(jokenode);
			}
			((JokeNodeView)view).setOnline(callback.isOnline);
		}else if(node instanceof Comment){
			Comment commentnode= (Comment)list.get(position);
			if (convertView == null||(convertView!=null&&!(convertView instanceof CommentView))) {
				view = new CommentView(callback,commentnode);
			} else {
				view = (CommentView) convertView;
				((CommentView)view).setNode(commentnode);
			}
		}
		// view.setExpended(node.isSelected);
		return view;
	}

}
